//
//  SubProductManagerVC.m
//  LazyCat
//
//  Created by linhui on 15/12/24.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "SubProductManagerVC.h"
#import "MJChiBaoZiHeader.h"
#import "MJChiBaoZiFooter.h"
#import "ProductCell.h"
#import "WebViewController.h"
#import "EditButton.h"
#import "FeWifiManHub.h"
@interface SubProductManagerVC ()<UIAlertViewDelegate,UITextFieldDelegate>
{
    NSMutableArray * _dataArray;
    UIView *_backTView;//没订单时背部提醒
    NSString * _urlIndex;//起始页
    BOOL _isLoading;
    NSString *_totalCount;//总页数
    NSDictionary *dataDic;
    NSString *_moneyStr;//成本全局变量
    NSString *_proID;//产品ID
    NSString *_isHot;//是否为推荐
    UITextField *_textField1;//编辑库存
    UIView *popView;
    UIView *_timeView;//库存编辑view
    int _keyH;//键盘高度
    NSString *_proName;//名字
    NSString *_proImg;
    NSIndexPath *_indexPath;//编辑库存刷新指定一行
    FeWifiManHub *_loading;
    NSString *_str;
    NSString *_kuncunNum;//修改的库存数
    NSString *_kuncunNumStr;//修改后库存数
    BOOL _isChangedKunCun;//是否改变了库存
    NSString *_CBStr;//成本
    NSString *_shoujiaStr;//售价
    BOOL _isMoneyChanged;//是否改变了售价
    NSArray *_editArr;//改变的数据源
}
@end
@implementation SubProductManagerVC
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //[self loadData:nil];
    [self registerForKeyboardNotifications];//键盘高度变化通知
    if ([AppData share].isLoadd == YES) {
        //[self loadDataaaa:nil];
        _urlIndex = @"1";
        [self loadData:nil];
    }
    [AppData share].isLoadd = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self loadData:nil];
    [AppData share].isLoadd = NO;
//    [self addRefresh];
    self.tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(addRefresh)];
    [self createPickerView];
}
- (void)createUI {
    self.view.backgroundColor = BackColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    [self.view addSubview:_backTView];
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:@"chanpin-no"];
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"抱歉,您暂时还没有产品";
    [_backTView addSubview:label];
    _urlIndex = @"1";
    _loading = [[FeWifiManHub alloc] initWithView:self.tableView withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 104, _loading.frame.size.width, _loading.frame.size.height);
    [self.tableView addSubview:_loading];
    [_loading show];
    _dataArray = [[NSMutableArray alloc]init];
    _isLoading = NO;
    MJRefreshAutoFooter *foot = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    self.tableView.footer = foot;
    _isChangedKunCun = NO;
    _isMoneyChanged = NO;
}
- (void)prepareForData {
    
}
- (void)loadData:(NSIndexPath *)indexPath {
    NSString *kUrl;
    if(self.currentPage == 0){
        kUrl = [NSString stringWithFormat:productManagerUrl,@"15",_urlIndex,[AppData share].username,@"",@"1"];
    }else if(self.currentPage == 1){
        kUrl = [NSString stringWithFormat:productManagerUrl,@"15",_urlIndex,[AppData share].username,@"",@"0"];
    }
    if ([_urlIndex isEqualToString:@"1"]) {
        [_dataArray removeAllObjects];
    }
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"products"];
        _editArr = arr;
        [_dataArray addObjectsFromArray:arr];
        _isLoading = NO;
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        if ([_totalCount isEqualToString:@"0"] || _totalCount == nil) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        [_loading dismiss];
        [_loading removeFromSuperview];
//        if (indexPath == nil) {
            [self.tableView reloadData];
//        }else {
//            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:(UITableViewRowAnimationNone)];
            
            //[self.tableView reloadData];
//            NSLog(@"row:------%ld",indexPath.row);
//            NSLog(@"section:------%ld",indexPath.section);
//            NSLog(@"urlindex:----%@",_urlIndex);
            //NSLog(@"%@",_dataArray);
//            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]
//                                        animated:YES
//                                  scrollPosition:UITableViewScrollPositionMiddle];
//        }
    }];
//    [_loading dismiss];
//    [_loading removeFromSuperview];
    if (kNetworkNotReachability) {
        [_loading dismiss];
        [_loading removeFromSuperview];
    }
}

//*----------/////
- (void)loadDataaaa:(NSIndexPath *)indexPath {
    NSString *kUrl;
    NSString *numCount;//数据量
    NSInteger count = ([_urlIndex integerValue] - 1) * 15 +_editArr.count;//数据量
    numCount = [NSString stringWithFormat:@"%ld",count];
    if(self.currentPage == 0){
        kUrl = [NSString stringWithFormat:productManagerUrl,numCount,@"1",[AppData share].username,@"",@"1"];
    }else if(self.currentPage == 1){
        kUrl = [NSString stringWithFormat:productManagerUrl,numCount,@"1",[AppData share].username,@"",@"0"];
    }
    [_dataArray removeAllObjects];
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"products"];
        [_dataArray addObjectsFromArray:arr];
        [self.tableView reloadData];
    }];
}
- (void)addRefresh {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
//    MJChiBaoZiHeader *header = [MJChiBaoZiHeader headerWithRefreshingBlock:^{
        _urlIndex = @"1";
//        [header beginRefreshing];
        [self loadData:nil];
    [self.tableView.header endRefreshing];
//    }];
//    self.tableView.header = header;
//    header.lastUpdatedTimeLabel.hidden = YES;
}
- (void)loadMore {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
        [[MessShowView share]showWithMess:@"没有更多数据"];
        return ;
    }else{
        _urlIndex = [NSString stringWithFormat:@"%ld",[_urlIndex integerValue]+1];
        [self loadData:nil];
    }
}
- (void)loadDataBBBBB:(NSIndexPath *)indexPath {
    NSString *kUrl;
//    NSString *numCount;//数据量
//    NSInteger count = ([_urlIndex integerValue] - 1) * 15 +_editArr.count;//数据量
//    numCount = [NSString stringWithFormat:@"%ld",count];
    if(self.currentPage == 0){
        kUrl = [NSString stringWithFormat:productManagerUrl,@"1",[NSString stringWithFormat:@"%ld",indexPath.row+1],[AppData share].username,@"",@"1"];
    }else if(self.currentPage == 1){
        kUrl = [NSString stringWithFormat:productManagerUrl,@"1",[NSString stringWithFormat:@"%ld",indexPath.row+1],[AppData share].username,@"",@"0"];
    }
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"products"];
        [_dataArray replaceObjectAtIndex:indexPath.row withObject:[arr firstObject]];
        [self.tableView reloadData];
    }];
}
#pragma mark -- 编辑库存
- (void)createPickerView {
    // 蒙版
    UIWindow *keyWindow=[UIApplication sharedApplication].keyWindow;
    popView=[[UIView alloc]initWithFrame:keyWindow.bounds];
    popView.backgroundColor=SetColor(0, 0, 0, .4);
    popView.alpha=0;
    [keyWindow addSubview: popView];
    UIControl *control = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 150)];
    [popView addSubview:control];
    [control addTarget:self action:@selector(hidentPopView) forControlEvents:UIControlEventTouchUpInside];
    //时间view
    _timeView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight-150, ScreenWidth, 150)];
    _timeView.backgroundColor = [UIColor whiteColor];
    [popView addSubview:_timeView];
//    UIButton *bcBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    bcBtn.tag = 270;
//    [bcBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
//    bcBtn.frame = CGRectMake(0, 0, ScreenWidth, 150);
//    [_timeView addSubview:bcBtn];
    
    //时间view上面的东西
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 45)];
    backView.backgroundColor = BackColor;
    [_timeView addSubview:backView];
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(0, 0, 60, 45);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:MainColor forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    cancelBtn.tag = 988;
    [cancelBtn addTarget:self action:@selector(sureOrFalseClicl:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:cancelBtn];
    UIButton *qdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    qdBtn.frame = CGRectMake(ScreenWidth-60, 0, 60, 45);
    [qdBtn setTitle:@"确定" forState:UIControlStateNormal];
    [qdBtn setTitleColor:MainColor forState:UIControlStateNormal];
    qdBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    qdBtn.tag = 977;
    [qdBtn addTarget:self action:@selector(sureOrFalseClicl:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:qdBtn];
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(60, 0, ScreenWidth-120, 45)];
    label1.text = @"编辑库存";
    label1.font = [UIFont systemFontOfSize:17];
    label1.textAlignment = NSTextAlignmentCenter;
    label1.textColor = SetColor(51, 51, 51, 1);
    [backView addSubview:label1];
    CGPoint center = _timeView.center;
    center.y = ScreenHeight-100;
    _textField1 = [[UITextField alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, 100, 200, 35)];
    _textField1.borderStyle = UITextBorderStyleRoundedRect;
    [_timeView addSubview:_textField1];
    _textField1.tag = 88;
    _textField1.keyboardType = UIKeyboardTypeNumberPad;
    _textField1.delegate = self;
    _textField1.font = [UIFont systemFontOfSize:14];
    _textField1.placeholder = @"请输入数量";
    NSArray *btnArr = @[@"增加库存",@"减少库存"];
    for (int i = 0;i<btnArr.count ; i++){
        EditButton *btn1 = [[EditButton alloc]init];
        btn1.frame = CGRectMake(i*100+(ScreenWidth/2 - 98), 50, 100, 40);
        btn1.tag = 20+i;
        [btn1 setTitle:btnArr[i] forState:UIControlStateNormal];
        [btn1 setImage:[UIImage imageNamed:@"no.png"] forState:UIControlStateNormal];
        [btn1 setImage:[UIImage imageNamed:@"yes.png"] forState:UIControlStateSelected];
        [btn1 addTarget:self action:@selector(addBtn:) forControlEvents:UIControlEventTouchUpInside];
        [_timeView addSubview:btn1];
        btn1.titleLabel.font = [UIFont systemFontOfSize:14];
    }
}
//编辑库存视图上的确定取消按钮方法
- (void)sureOrFalseClicl:(UIButton *)sender {
    UIButton *add = (UIButton *)[_timeView viewWithTag:20];
    UIButton *addno = (UIButton *)[_timeView viewWithTag:21];
    if (sender.tag == 988) {//取消
        [self hidentPopView];
    }else if (sender.tag == 977){//确定
        if ((add.selected == NO && addno.selected == NO) || _textField1.text.length == 0) {//信息输入不全
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"未选择或信息不完整" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }else {//确定提交接口
            NSString *name;
            NSString *url;
        if(add.selected == YES){
                name = _textField1.text;
                url = [NSString stringWithFormat:EditKuCunUrl,_proID,name];
            }else if (addno.selected == YES){
                name = [NSString stringWithFormat:@"-%@",_textField1.text];
                url = [NSString stringWithFormat:EditKuCunUrl,_proID,name];
            }
            [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
                NSDictionary *dic = networkRequest.responseData;
                NSString *result = [dic objectForKey:@"m"];
                if ([result isEqualToString:@"success"]) {
//                    [self loadData:_indexPath];//刷新指定一行
//                    _isChangedKunCun = YES;
//                    _kuncunNum = name;
//                    NSLog(@"%@",_kuncunNum);
//                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:_indexPath, nil] withRowAnimation:(UITableViewRowAnimationNone)];
                    //[self loadDataaaa:nil];
                    [self loadDataBBBBB:_indexPath];
                    [[MessShowView share]showWithMess:@"操作成功" login:YES];
                    [self hidentPopView];
                }else  {
                    [[MessShowView share]showWithMess:result login:NO];
                }
            }];
        }
    }
}
- (void)addBtn:(UIButton *)sender {
    UIButton *add = (UIButton *)[_timeView viewWithTag:20];
    UIButton *addno = (UIButton *)[_timeView viewWithTag:21];
    if (sender.tag == 20) {//增加库存
        if (sender.selected == YES) {
            sender.selected = NO;
        }else {
            sender.selected = YES;
            addno.selected = NO;
        }
    }else if (sender.tag == 21){//减少库存
        if (sender.selected == YES) {
            sender.selected = NO;
            
        }else {
            sender.selected = YES;
            add.selected = NO;
        }
    }
}
-(void)mengBan {
    [UIView animateWithDuration:0.2 animations:^{
        popView.alpha=1;
        _timeView.frame = CGRectMake(0, ScreenHeight - 150, ScreenWidth, 150);
    }];
}
-(void)hidentPopView {
    CGPoint center = _timeView.center;
    center.y = ScreenHeight+75;
    [UIView animateWithDuration:0.2 animations:^{
        //设置要被动画的那个视图
        //在动画结束时，它的属性处于什么状态
        _timeView.center = center;
        popView.alpha = 0;
    }];
    _textField1.text = nil;//隐藏view时将textfield内容置为空。
    [_textField1 resignFirstResponder];
}
#pragma mark -- 键盘高度
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
}
#pragma mark -- 键盘高度
//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
//- (void)keyboardWasShown:(NSNotification*)aNotification
//{
//    NSDictionary* info = [aNotification userInfo];
//    //kbSize即為鍵盤尺寸 (有width, height)
//    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
//    if(kbSize.height == 216)
//    {
//        _keyH = 216;
//    }
//    else
//    {
//        _keyH = 36+216;   //252 - 216 系统键盘的两个不同高度
//    }
//    [UIView animateWithDuration:0.2 animations:^{
//        //popView.alpha=1;
//        _timeView.frame = CGRectMake(0, ScreenHeight - (_keyH +150), ScreenWidth, 150);
//    }];
//}
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
    
    CGRect inputFieldRect = _timeView.frame;
    
    if (inputFieldRect.origin.y == ScreenHeight - 150) {
        if (_textField1.editing) {
            inputFieldRect.origin.y += yOffset;
        }
    }else {
        inputFieldRect.origin.y += yOffset;
    }
    [UIView animateWithDuration:duration animations:^{
        _timeView.frame = inputFieldRect;
    }];
}
#pragma mark -- cell上按钮点击方法
- (void)btnClick:(UIButton *)sender event:(id)event {
    //取indexpath
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath= [self.tableView indexPathForRowAtPoint:currentTouchPosition];
    _indexPath = indexPath;
    if (indexPath!= nil)
    {
        NSLog(@"我在第%ld行，编号%ld",(long)indexPath.row,(long)sender.tag);
        if (sender.tag == 1110) {//上架
            if (indexPath.row < [_dataArray count]) {
            _proID = [_dataArray[indexPath.row]objectForKey:@"userproductid"];
            }
            NSString *url = [NSString stringWithFormat:shangXiaJiaProduct,_proID,@"1"];
            [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
                NSDictionary *dic = networkRequest.responseData;
                NSString *result = [dic objectForKey:@"m"];
                if ([result isEqualToString:@"success"]) {
                    [[MessShowView share]showWithMess:@"商品上架成功" login:YES];
                    if (indexPath.row < [_dataArray count]) {
//                        [_dataArray removeObjectAtIndex:indexPath.row];
//                        [self.tableView reloadData];
                        [self loadDataaaa:nil];
                    }
                    [AppData share].isLoadd = YES;//改变刷新
//                    if (indexPath.row < [_dataArray count])  {
//                        [_dataArray removeObjectAtIndex:indexPath.row];
//                    }
//                    if (_dataArray.count < 1) {
//                        [self loadData:nil];
//                    }else {
//                    [self.tableView reloadData];
//                    }
                }else  {
                    [[MessShowView share]showWithMess:result login:NO];
                }
            }];
//            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"确认上架" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
//            alertView.tag = 685;
//            [alertView show];
            
        }else if (sender.tag == 1111) {//下架
            if (indexPath.row < [_dataArray count]) {
            _proID = [_dataArray[indexPath.row]objectForKey:@"userproductid"];
            }
            NSString *url = [NSString stringWithFormat:shangXiaJiaProduct,_proID,@"0"];
            [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
                NSDictionary *dic = networkRequest.responseData;
                NSString *result = [dic objectForKey:@"m"];
                if ([result isEqualToString:@"success"]) {
                    //[self loadData:nil];
                    if (indexPath.row < [_dataArray count]) {
//                        [_dataArray removeObjectAtIndex:indexPath.row];
//                        [self.tableView reloadData];
                        [self loadDataaaa:nil];
                    }
                    [AppData share].isLoadd = YES;//改变刷新
//                    if (indexPath.row < [_dataArray count])  {
//                        [_dataArray removeObjectAtIndex:indexPath.row];
//                    }
//                    if (_dataArray.count < 1) {
//                        [self loadData:nil];
//                    }else {
//                        [self.tableView reloadData];
//                    }
                    [[MessShowView share]showWithMess:@"商品下架成功" login:YES];
                }else  {
                    [[MessShowView share]showWithMess:result login:NO];
                }
                //[self.tableView reloadData];
                //[self addRefresh];
            }];
//            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"确认下架" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
//            alertView.tag = 686;
//            [alertView show];
        }else if (sender.tag == 1112){//设为推荐
            if (indexPath.row < [_dataArray count]) {
                _isHot = _dataArray[indexPath.row][@"ishot"];
            }
//            NSString *message;
//            if ([_isHot isEqualToString:@"1"]) {
//                message = @"取消推荐";
//            }else {
//                message = @"确认推荐";
//            }
//            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:message delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
//            alertView.tag = 687;
            
//            [alertView show];
            if (indexPath.row < [_dataArray count]) {
                _proID = [_dataArray[indexPath.row]objectForKey:@"userproductid"];
            }
            NSString *url;
            if ([_isHot isEqualToString:@"1"]) {
                url = [NSString stringWithFormat:isRecommend,_proID,@""];
            }else {
                url = [NSString stringWithFormat:isRecommend,_proID,@"1"];
            }
            [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
                NSDictionary *dic = networkRequest.responseData;
                NSString *result = [dic objectForKey:@"m"];
                if ([result isEqualToString:@"success"]) {
                    //[self loadDataaaa:nil];
                    [self loadDataBBBBB:_indexPath];
                    [[MessShowView share]showWithMess:@"操作成功" login:YES];
                }else  {
                    [[MessShowView share]showWithMess:result login:NO];
                }
            }];
        }else if (sender.tag == 1113){
            if (indexPath.row < [_dataArray count]) {
            _proID = [_dataArray[indexPath.row]objectForKey:@"userproductid"];
            _proName = [_dataArray[indexPath.row]objectForKey:@"productname"];
            _proImg = [_dataArray[indexPath.row]objectForKey:@"img"];
            }
            [self fenXiangAction];
        }else if (sender.tag == 1114){//成本价售价保存-----
            ProductCell *cell = (ProductCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            if (indexPath.row < [_dataArray count]) {
            _proID = [_dataArray[indexPath.row]objectForKey:@"userproductid"];
            }
            _moneyStr = cell.chengBenTextF.text;//成本价
            _shoujiaStr = cell.shouJiaTextF.text;//售价
            NSString *url = [NSString stringWithFormat:editProductUrl,_proID,_moneyStr,_shoujiaStr];
            [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
                NSDictionary *dic = networkRequest.responseData;
                NSString *result = [dic objectForKey:@"m"];
                if ([result isEqualToString:@"success"]) {
                    sender.hidden = YES;
//                    _isMoneyChanged = YES;
//                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:_indexPath, nil] withRowAnimation:(UITableViewRowAnimationNone)];
                    //[self loadDataaaa:nil];
                    [self loadDataBBBBB:_indexPath];
                    [[MessShowView share]showWithMess:@"操作成功" login:YES];
                }else  {
                    [[MessShowView share]showWithMess:result login:NO];
                }
            }];
            [cell.chengBenTextF resignFirstResponder];
            [cell.shouJiaTextF resignFirstResponder];
        }else if (sender.tag == 2016){//库存编辑按钮----
            ProductCell *cell = (ProductCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            _kuncunNumStr = cell.kuCunLabel.text;
            NSLog(@"%@",_kuncunNumStr);
            if (indexPath.row < [_dataArray count]) {
            _proID = [_dataArray[indexPath.row]objectForKey:@"userproductid"];
            }
            _indexPath = indexPath;
            [self.view endEditing:YES];
//            ProductCell *cell = (ProductCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            cell.baoCunBtn.hidden = YES;
            [self mengBan];//显示库存编辑view
        }else if (sender.tag == 6666){//进入详情
            WebViewController *detailWeb = [[WebViewController alloc]init];
            if (kNetworkNotReachability) { // 没网
                [[MessShowView share] showWithMess:@"当前网络不给力"];
                return;
            }else {
                if (indexPath.row < [_dataArray count]) {
                    detailWeb.requestUrl = [_dataArray[indexPath.row]objectForKey:@"userproductid"];
                    detailWeb.classID = [_dataArray[indexPath.row]objectForKey:@"categoryid"];
                    detailWeb.className = [_dataArray[indexPath.row]objectForKey:@"categoryname"];
                    detailWeb.isHot = [_dataArray[indexPath.row]objectForKey:@"ishot"];
                    detailWeb.isShangJia = [NSString stringWithFormat:@"%ld",_currentPage];
                    detailWeb.PName = [NSString stringWithFormat:@"%@",[_dataArray[indexPath.row]objectForKey:@"productname"]];
                    detailWeb.PImg = [NSString stringWithFormat:@"%@",[_dataArray[indexPath.row]objectForKey:@"img"]];
                    
                    
                }
                if (_myBlock) {//跳转页面
                    _myBlock(detailWeb);
                }
            }
            
        }else if (sender.tag == 270){
            NSLog(@"6666");
        }
    }
}
- (void)bcViewBtn:(UIButton *)sender {
    
}
// 分享
-(void)fenXiangAction {
    NSString *url = [NSString stringWithFormat:@"%@/LCat/Product-%@?appname=lanmao&plat=ios&username=%@&iszhanggui=1&sign2=%@",BaseUrl,_proID,[AppData share].username,[Utils md5SignStr]];
    [[ShareView share] showMess:[NSString stringWithFormat:@"%@%@",_proName,url] withImgUrl:_proImg url:url];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productcell"];
//    cell = nil;
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"ProductCell" owner:nil options:nil][0];
        cell.tuiJianBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    }
//    else {
//        [cell removeFromSuperview];//处理重用
//          }
    [cell.xiaJiaBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.shangJiaBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.tuiJianBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.fenXiangBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.baoCunBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.editBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.inBtnClicl addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];//进入详情按钮
    [cell.inBtnClick2 addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];//进入详情按钮
    cell.backgroundColor = BackColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //产品数组
    if (indexPath.row < [_dataArray count]) {////////防止数组越界
        if (_currentPage == 0) {
            cell.xiaJiaBtn.hidden = NO;
            cell.shangJiaBtn.hidden = YES;
        }else if (_currentPage == 1){
            cell.shangJiaBtn.hidden = NO;
            cell.xiaJiaBtn.hidden = YES;
        }
        if ([_dataArray[indexPath.row][@"ishot"]isEqualToString:@"1"]) {//是否为推荐
            [cell.tuiJianBtn setTitle:@"已推荐" forState:UIControlStateNormal];
            [cell.tuiJianBtn setTitleColor:MainColor forState:UIControlStateNormal];
            [cell.tuiJianBtn setImage:[UIImage imageNamed:@"tuijian"] forState:UIControlStateNormal];
            
            cell.tuiJianBtn.imageEdgeInsets = UIEdgeInsetsMake(4, 5, 4, 50);
            cell.tuiJianBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        }else {
            [cell.tuiJianBtn setTitle:@"推荐" forState:UIControlStateNormal];
            [cell.tuiJianBtn setTitleColor:SetColor(102, 102, 102, 1) forState:UIControlStateNormal];
            [cell.tuiJianBtn setImage:[UIImage imageNamed:@"chanpian_small_tuijian"] forState:UIControlStateNormal];
            cell.tuiJianBtn.imageEdgeInsets = UIEdgeInsetsMake(4, 10, 4, 40);
            cell.tuiJianBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        }
        cell.titleLabel.text = [_dataArray[indexPath.row]objectForKey:@"productname"];
//        if (_isChangedKunCun) {
//            if (indexPath == _indexPath) {
//                NSInteger sum = [_kuncunNumStr integerValue];
//                sum +=  [_kuncunNum integerValue];
//                cell.kuCunLabel.text = [NSString stringWithFormat:@"%ld",sum];//库存
//            }
//            _isChangedKunCun = NO;
        //}else {
            cell.kuCunLabel.text = [NSString stringWithFormat:@"%@",[_dataArray[indexPath.row]objectForKey:@"numtotalstock"]];//库存
        //}
        cell.kuCunLabel.adjustsFontSizeToFitWidth = YES;
        cell.xiaoLiangLabel.text = [NSString stringWithFormat:@"销量:%@",[_dataArray[indexPath.row]objectForKey:@"numrealbuy"]];
//        if (_isMoneyChanged) {
//            if (indexPath == _indexPath) {
//                cell.shouJiaTextF.text = _shoujiaStr;
//                cell.chengBenTextF.text = _moneyStr;
//            }
//            _isMoneyChanged = NO;
//        }else {
            cell.shouJiaTextF.text = [_dataArray[indexPath.row]objectForKey:@"saleprice"];//价格
            cell.chengBenTextF.text = [_dataArray[indexPath.row]objectForKey:@"costprice"];//成本
//        }
        //售价输入框
        cell.shouJiaTextF.textColor = MainColor;
        cell.shouJiaTextF.font = [UIFont systemFontOfSize:12];
        cell.shouJiaTextF.tag = 2222;
        [cell.shouJiaTextF addTarget:self action:@selector(textfieldChange:) forControlEvents:UIControlEventEditingChanged];
        cell.shouJiaTextF.autocorrectionType = UITextAutocorrectionTypeNo;
        //textField.autocorrectionType=UITextAutocorrectionTypeNo;
        cell.shouJiaTextF.delegate = self;
        cell.shouJiaTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        //成本价输入框
        cell.chengBenTextF.text = [_dataArray[indexPath.row]objectForKey:@"costprice"];
        cell.chengBenTextF.font = [UIFont systemFontOfSize:12];
        [cell.iconImage sd_setImageWithURL:[NSURL URLWithString:[_dataArray[indexPath.row]objectForKey:@"img"]] placeholderImage:[UIImage imageNamed:@"product-no-pic"]];
        cell.chengBenTextF.adjustsFontSizeToFitWidth = YES;
        cell.chengBenTextF.delegate = self;
        cell.chengBenTextF.tag = 2223;
        [cell.chengBenTextF addTarget:self action:@selector(textfieldChange:) forControlEvents:UIControlEventEditingChanged];
        cell.chengBenTextF.autocorrectionType = UITextAutocorrectionTypeNo;
        cell.chengBenTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        [cell.chengBenTextF setValue:[UIFont boldSystemFontOfSize:11] forKeyPath:@"_placeholderLabel.font"];
    }
    [cell.subviews[0] setBackgroundColor:[UIColor clearColor]];
     [cell setNeedsDisplay];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 180;
}
#pragma mark -- uitextfield代理方法
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField.tag == 2222 || textField.tag == 2223) {
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0) {
            UIView *v = [textField superview];
            UIView *vv = [v superview];
            UIView *vvv = [vv superview];
            NSLog(@"%f",[[[UIDevice currentDevice] systemVersion] doubleValue]);
            ProductCell *cell = (ProductCell *)[vvv superview];
            NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];
            _indexPath = indexpath;
            cell.baoCunBtn.hidden = NO;
        }else {
            UIView *v = [textField superview];
            UIView *vv = [v superview];
            ProductCell *cell = (ProductCell *)[vv superview];
            NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];
            _indexPath = indexpath;
            cell.baoCunBtn.hidden = NO;
        }
        self.tableView.allowsSelection = NO;//设置tableview为不可选.
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 2222 || textField.tag == 2223) {
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0) {
            UIView *v = [textField superview];
            UIView *vv = [v superview];
            UIView *vvv = [vv superview];
            NSLog(@"%f",[[[UIDevice currentDevice] systemVersion] doubleValue]);
            ProductCell *cell = (ProductCell *)[vvv superview];
            cell.baoCunBtn.hidden = YES;
        }else {
            UIView *v = [textField superview];
            UIView *vv = [v superview];
            ProductCell *cell = (ProductCell *)[vv superview];
            cell.baoCunBtn.hidden = YES;
        }
    }else if (textField.tag == 88){
        //textField.text = nil;
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
#pragma mark -- 词频所有词变更判断
- (void)textfieldChange:(UITextField *)textField {
    NSLog(@"1234567890-");
    if (textField.tag == 2222) {
        if ([self validateNumber:textField.text]) {
            _str = textField.text;
        }else {
            textField.text = _str;
        }
    }else if (textField.tag == 2223){
        if ([self validateNumber:textField.text]) {
            _CBStr = textField.text;
        }else {
            textField.text = _CBStr;
        }
    }
}
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //if (textField == _textField1) {
    NSScanner      *scanner    = [NSScanner scannerWithString:string];
    NSCharacterSet *numbers;
    NSRange         pointRange = [textField.text rangeOfString:@"."];
    
    if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
    {
        numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    }
    else
    {
        if (textField == _textField1) {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }else {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
    }
    
    if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
    {
        return NO;
    }
    
    short remain = 2; //默认保留2位小数
    
    NSString *tempStr = [textField.text stringByAppendingString:string];
    NSUInteger strlen = [tempStr length];
    if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
        if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
            return NO;
        }
        if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
            return NO;
        }
    }
    NSRange zeroRange = [textField.text rangeOfString:@"0"];
    if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
        if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
            textField.text = string;
            return NO;
        }else{
            if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                if([string isEqualToString:@"0"]){
                    return NO;
                }
            }
        }
    }
    NSString *buffer;
    if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
    {
        return NO;
    }
    //}
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
